<template>
  <div>
    <el-form 
      :model="formValues"
      :rules="rules"
      ref="form"
      label-width="100px"
      class="generation-content"
      size="small"
      :inline="true"
    >
      <el-form-item label="公司名称" prop="name">
        <el-input v-model="formValues.name" placeholder="请输入公司名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button v-if="!isLoading" type="primary" @click="submitForm('form')">生成</el-button>
        <el-button v-else type="primary" :disabled="true" :loading="isLoading" >生成中...</el-button>
      </el-form-item>
    </el-form>
    <div class="progress-container" v-if="isLoading">
      <div 
        class="progress-bar"
        :style="{ width: percentage + '%' }"
      >
        <span class="progress-text">{{ percentage }}%</span>
      </div>
    </div>
  </div>
</template>
<script>
  import { Message } from 'element-ui';
  import errorCode from '@/utils/errorCode';
  import { blobValidate } from "@/utils/ruoyi";
  import { saveAs } from 'file-saver';
  import { getGenerationFile, getProgress, downloadGenerationFile } from "@/api/ai/agent";

  export default {
    name: "Generation",
    data() {
      return {
        timerId: null,
        percentage: 0,
        isLoading: false,
        formValues: { name: '',},
        rules: {
          name: [
            { required: true, message: '请输入公司名称', trigger: 'blur' },
          ],
        }
      };
    },
    beforeDestroy() {
      if (this.timerId) {
        clearInterval(this.timerId); // 清除定时器
        this.timerId = null; // 设置为null，防止后续误操作
      }
    },
    methods: {
      // 清理定时器
      cancelPolling(){
        clearInterval(this.timerId);
        this.timerId = null;
      },
      // 获取当前生成进度
      fetchPolling(){
        getProgress(this.$store.state.user.id).then((res)=>{
          if(res?.code === 200){
            const { total = 0, finish = 0 } = res?.data || {};
            if (total === finish) {
              this.percentage = 99;
              this.cancelPolling();
              setTimeout(function() {
                downloadGenerationFile().then(async (data) => {
                  this.isLoading = false;
                  this.percentage = 100;
                  const isBlob = blobValidate(data);
                  if (isBlob) {
                    const blob = new Blob([data],{
                      type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                    })
                    saveAs(blob, `${this?.formValues?.name || ''}信贷报告`)
                  } else {
                    const resText = await data.text();
                    const rspObj = JSON.parse(resText);
                    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
                    Message.error(errMsg);
                  }
                }).catch(() => {
                  this.isLoading = false;
                });
              }, 5000);
            }else{
              this.percentage = Math.round(finish / total * 10000) / 100 || 1;
            }
          }
        })
      },
      // 生成信贷报告，未使用公共文件下载方式，如果使用需要后端修改参数类型
      submitForm(formName) {
        this.$refs[formName].validate((valid,) => {
          if (valid) {
            this.isLoading = true;
            this.percentage = 1;
            try {
              getGenerationFile({ content: this?.formValues?.name });
              if (this.timerId) cancelPolling();
              this.timerId = setInterval(this.fetchPolling, 5000);
            } catch (error) {
              this.isLoading = false;
            }
          } else {
            return false;
          }
        });
      },
    }
  }
</script>
<style lang="scss">
  .generation-content {
    margin-top: 16px;
  }
  .progress-container {
    margin: 48px 52px;
    // width: 100%;
    height: 22px;
    background-color: #f0f0f0;
    border-radius: 15px;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    position: relative;
  }

  .progress-bar {
    height: 100%;
    background: linear-gradient(45deg, #409eff, #409eff);
    border-radius: 15px;
    transition: width 0.5s ease-in-out;
    position: relative;
    overflow: hidden;
  }

  .progress-bar::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background-image: linear-gradient(
      -45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
    background-size: 50px 50px;
    animation: moveStripes 2s linear infinite;
  }

  .progress-text {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: white;
    font-weight: bold;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  }
</style>